package com.lingjtx.common.security.limit;

import com.lingjtx.common.core.RedisOptions;
import com.lingjtx.common.core.ResponseResult;
import com.lingjtx.common.core.constant.Const;
import com.lingjtx.common.core.token.UserVo;
import com.lingjtx.common.core.util.BeanUtil;
import com.lingjtx.common.core.util.ParamCheck;
import com.lingjtx.common.security.annotation.NonRepeatable;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
public class NonRepeatableState extends HandlerState<ProceedingJoinPoint, HttpServletRequest> {
    @Override
    public ResponseResult<Object> retError() {
        return ResponseResult.createByError("请不要重复提交数据！");
    }

    @Override
    public void handler(ProceedingJoinPoint point, HttpServletRequest request, RedisOptions redis) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        NonRepeatable annotation = signature.getMethod().getAnnotation(NonRepeatable.class);
        if (Objects.nonNull(annotation)) {
            Object[] args = point.getArgs();
            if (args != null && args.length > 0) {
                String token = request.getHeader(Const.AuthTokenMap.AUTHORIZATION);
                UserVo user = (UserVo) redis.get(token);
                if (user != null) {
                    ParamCheck check = ParamCheck.init()
                            .addParamMap(BeanUtil.covertMap(args[0])) // 规定表单提交数据第一个参数就是表单POJO
                            .addRedisService(redis)
                            .addExpireTime(annotation.value())
                            .addRequestUri(request.getRequestURI())
                            .addUserUid(user.getUserId())
                            .removeDefaultKey()
                            .hash();
                    if (check.repeatable()) {
                        super.setErrorState(true);
                    }
                }
            }
        }
    }
}
